package com.mzj.saas.mservice.records.service;


import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.application.entity.HousePutRecordsSet;
import com.mzj.saas.mservice.application.repository.HousePutRecordsSetRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class RecordsPCService {
    private static final Logger LOG = LoggerFactory.getLogger(RecordsPCService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private HousePutRecordsSetRepository housePutRecordsSetRepository;

    /*
     *信息备案列表显示
     *type 0 待确认 1 已确认
     */
    public ResultBean<Object> recordsListShow(String accessToken, Integer pageNumber, Integer pageSize, Integer type, String name) {
        LOG.info("RecordsPCService recordsListShow accessToken={},pageNumber={},pageSize={},type={},name={},recordStatus={}", accessToken, pageNumber, pageSize, type, name);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            if (departmentHierarchy == null) {
                return ResultBean.failedResultWithMsg("当前企业层级关系不存在");
            }
            // 查询当前企业层级架构下的所有产权单位
            String sql = "SELECT org_id FROM ( SELECT t1.id,t1.org_id,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM ( SELECT id,parent_id,org_id FROM `saas_department_hierarchy` t ORDER BY parent_id, id ) t1,(SELECT @pids := ?) t2 ) t3 WHERE ischild != 0 \n";
            List<Long> orgIdList = jdbcTemplate.queryForList(sql, new Object[]{departmentHierarchy.getId()}, Long.class);
            orgIdList.add(tokenRedisVo.getEnterpriseId());
            // 产权单位下所有房屋id
            List<House> houseList = houseRepository.findByOrgIdIn(orgIdList);
            String recordsSql = "SELECT h.id AS houseId,h.org_id AS orgId,h.community_id AS communityId,u.match_user_id AS matchUserId,"
                    + "u.name1,u.name2,u.apply_id AS applyId,r.`id` AS recordsId,r.`submit_time` AS submitTime,r.`status`,r.`confirm_time` AS confirmTime \n" +
                    " FROM (SELECT * FROM saas_house h WHERE h.payment_status = 1) h \n" +
                    " LEFT JOIN (SELECT m.id,m.match_user_id,m.apply_id,m.house_id,a1.name AS name1,a2.name AS name2 "
                    + "FROM saas_house_match_user m "
                    + "LEFT JOIN `saas_app_user` a1 ON  m.`match_user_id`=a1.`id`"
                    + "LEFT JOIN `saas_app_user` a2 ON  m.`match_user_id`=a2.`enterprise_user_id` WHERE m.status = 1 AND (a1.name IS NOT NULL AND a2.name IS NOT NULL)) u \n" +
                    " ON h.id = u.`house_id` LEFT JOIN saas_house_put_records r ON h.id = r.`house_id` \n" +
                    " WHERE  1=1 ";
            StringBuffer houseIds = new StringBuffer();
            for (House house : houseList) {
                houseIds.append("'").append(house.getId()).append("'").append(",");
            }
            String houseId = houseIds.substring(0, houseIds.lastIndexOf(","));
            String offsets = "   LIMIT ? OFFSET ? ";
            recordsSql += "   AND  h.`id` IN (" + houseId + ")";
            if (type != null) {
                recordsSql += "  AND r.`status`=" + type;
            }
            List<Object> args = new ArrayList<>();
            StringBuilder where = new StringBuilder();
            if (StringUtils.isNotBlank(name)) {
                where.append("  AND  (u.`name1` like ? or u.`name2` like ?)  \n");
                args.add("%" + name + "%");
                args.add("%" + name + "%");
            }
            // 查询总记录数
            String count = "select count(1) FROM (" + recordsSql + where + ") c  ";
            Long total = jdbcTemplate.queryForObject(count, Long.class, args.toArray());
            LOG.info("SQL :" + recordsSql + where);
            if (total == 0) {
                result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                result.setResultData(null);
                return result;
            }
            // 查询分页数据
            where.append("  ORDER BY ").append(" r.submit_time desc ").append(" \n").append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<Map<String, Object>> resultList = jdbcTemplate.queryForList(recordsSql + where, args.toArray());
            for (Map<String, Object> map : resultList) {
                String matchUserId = String.valueOf(map.get("matchUserId"));
                Long communityId = Long.valueOf(String.valueOf(map.get("communityId")));
                if (tokenRedisVo.getId().equals(matchUserId == null ? "" : matchUserId)) {
                    map.put("matchUserFlag", 1);
                } else {
                    map.put("matchUserFlag", 0);
                }
                HousePutRecordsSet set = housePutRecordsSetRepository.findByAreaIdAndStatus(communityId, 1);
                /*if (set == null) {
                    return ResultBean.failedResultWithMsg("社区未设置信息备案确认人");
                }*/
                if (set != null && set.getConfirmorId().equals(tokenRedisVo.getId())) {
                    map.put("confirmFlag", 1);
                } else {
                    map.put("confirmFlag", 0);
                }

                // 承租人姓名处理
                String name1 = String.valueOf(map.get("name1"));
                String name2 = String.valueOf(map.get("name2"));
                if (StringUtils.isNotEmpty(name1)) {
                    map.put("name", name1);
                } else {
                    map.put("name", name2);
                }
            }
            apiData.setData(resultList);
            apiData.setTotal(total);
            // LOG.info("SQL :" + recordsSql + where);
            result.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
